import Vue from 'vue'
import Vuex from 'vuex'
import {getItem, setItem} from "@/utils/storage"
import router from "@/router"

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    userinfo: getItem("userinfo") || null,
    token: getItem("token") || null,
    tabs: []
  },
  mutations: {
    setUserInfo: (state, payload) => {
      setItem("userinfo", payload)
      state.userinfo = payload
    },
    setToken: (state, payload) => {
      setItem("token", payload)
      state.token = payload
    },
    addTab: (state, tab) => {
      state.tabs.push(tab)
    }
  },
  actions: {
    login({commit}, payload) {
      commit("setUserInfo", payload.userinfo)
      commit("setToken", payload.token)
    },
    logout({commit}) {
      commit("setUserInfo", null)
      commit("setToken", null)
    },
    openMenuItem({commit, state}, payload) {
      if (!state.tabs.find(item => item.path === payload.path)){
        commit("addTab", payload)
      }
    },
    closeMenuItem({commit, state}, {path, isActive}) {
      console.log(path, isActive)
      const {tabs} = state
      const index = tabs.findIndex(item => item.path === path)
      if (index === -1) return
      tabs.splice(index, 1)

      if (!isActive) return
      if (!tabs.length) {
        router.push("/")
      } else {
        // [0, 1, 2]
        const targetIndex = index === tabs.length ? index -1 : index
        router.push(tabs[targetIndex].path)
      }

    }
  },
  modules: {
  }
})
